
package com.epam.android.training.day4day5.task1;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RemoteViews;

/**
 * Main activity of task1 application which is able to create
 * {@link SupportActivity}.
 * 
 * @author Anton Novikau
 */
public class MainActivity extends Activity {

    private static final int HELLO_NOTIFICATION_ID = 1;

    private static final int HELLO_DIALOG_ID = 2;

    private static final int VALIDATION_DIALOG_ID = 3;

    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // set start new activity button action.
        Button createActivity = (Button) findViewById(R.id.button_start_activity);
        createActivity.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (isFormValid()) {
                    startSupportActivity();
                } else {
                    showDialog(VALIDATION_DIALOG_ID);
                }

            }
        });

        // set dialog me button action
        Button dialogMe = (Button) findViewById(R.id.dialog_me);
        dialogMe.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                showDialog(HELLO_DIALOG_ID);
            }

        });

        // set notify me button action
        Button notifyMe = (Button) findViewById(R.id.notify_me);
        notifyMe.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                showNotification();
            }
        });
    }

    /**
     * Initialize the contents of the Activity's standard options menu.
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    /**
     * This hook is called whenever an item in your options menu is selected.
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        boolean status;
        switch (item.getItemId()) {
            case R.id.add_age:
                View ageRow = findViewById(R.id.age_row);
                ageRow.setVisibility(View.VISIBLE);
                status = true;
                break;
            default:
                status = super.onOptionsItemSelected(item);
                break;
        }
        return status;
    }

    /**
     * Callback for creating dialogs that are managed (saved and restored) for
     * you by the activity.
     */
    @Override
    protected Dialog onCreateDialog(int id) {
        Dialog result;
        switch (id) {
            case HELLO_DIALOG_ID:
                result = createHelloDialog();
                break;
            case VALIDATION_DIALOG_ID:
                result = createValidationDialog();
                break;
            default:
                result = super.onCreateDialog(id);
                break;
        }
        return result;
    }

    private void startSupportActivity() {
        Intent intent = new Intent(MainActivity.this, SupportActivity.class);

        intent.putExtras(collectFormData());
        startActivity(intent);
    }

    private Bundle collectFormData() {

        Bundle data = new Bundle();

        final EditText firstName = (EditText) findViewById(R.id.first_name);
        final EditText lastName = (EditText) findViewById(R.id.last_name);
        final EditText age = (EditText) findViewById(R.id.age);

        Resources resources = getResources();
        String firstNameKey = resources.getString(R.string.first_name_bundle_key);
        String lastNameKey = resources.getString(R.string.last_name_bundle_key);
        String ageKey = resources.getString(R.string.age_bundle_key);

        data.putString(firstNameKey, firstName.getText().toString());
        data.putString(lastNameKey, lastName.getText().toString());
        String ageText = age.getText().toString();
        try {
            data.putInt(ageKey,
                    (ageText != null && ageText.length() > 0) ? Integer.parseInt(ageText) : -1);
        } catch (NumberFormatException e) {
            Log.e(MainActivity.class.getSimpleName(), "age is not a number.");
        }

        return data;
    }

    private Dialog createHelloDialog() {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);

        dialogBuilder.setMessage(R.string.dialog_message).setTitle(R.string.dialog_header)
                .setNeutralButton(R.string.ok_button, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
        return dialogBuilder.create();
    }

    private Dialog createValidationDialog() {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);

        dialogBuilder
                .setMessage(R.string.validation_message)
                .setPositiveButton(R.string.send_anyway_button,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                startSupportActivity();
                            }
                        })
                .setNegativeButton(R.string.cancel_button, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

        return dialogBuilder.create();
    }

    private void showNotification() {
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        Bundle data = collectFormData();
        Resources resources = getResources();

        String ticker = resources.getString(R.string.notification_header);
        Notification notification = new Notification(R.drawable.icon, ticker,
                System.currentTimeMillis());

        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.greeting_notification);
        remoteViews.setImageViewResource(R.id.notification_image, R.drawable.icon);
        String greeting = ResourcesUtil.formatGreeting(resources, data);
        remoteViews.setTextViewText(R.id.notification_text, greeting);
        notification.contentView = remoteViews;

        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        notification.contentIntent = contentIntent;

        notificationManager.notify(HELLO_NOTIFICATION_ID, notification);
    }

    private boolean isFormValid() {
        Editable firstName = ((EditText) findViewById(R.id.first_name)).getText();
        Editable lastName = ((EditText) findViewById(R.id.last_name)).getText();
        return firstName != null && lastName != null && firstName.length() > 0
                && lastName.length() > 0;
    }
}
